//
//  SNEquipmentScreenViewController.m
//  project
//
//  Created by 张淋 on 2019/5/7.
//  Copyright © 2019 黄建华. All rights reserved.
//

#import "SNEquipmentScreenViewController.h"
#import "JHFeilterManager.h"
#import "SNEquipmentScreenImageView.h"
#import "ZJSwitch.h"
#import "OTAShowView.h"

@interface SNEquipmentScreenViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) SNEquipmentScreenImageView *equipmentScreenSettingView;
@property (nonatomic, strong) OTAShowView                *showView;
@property (nonatomic, strong) UIView                     *bgView;
@property (nonatomic, assign) BOOL                       isChangePhoto;
@property (nonatomic, assign) int                        stepHeight;
@property (nonatomic, assign) int                        timeHeight;
@property (nonatomic, strong) NSMutableArray             *array;
@property (nonatomic, strong) UIImage                    *saveImage;

@end

@implementation SNEquipmentScreenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SNCOLORWHITE;

//    if ([self getDocumentImage]) {
//        _isChangePhoto = NO;
//        NSLog(@"å🙂开始 没有保存图片>>>%i", _isChangePhoto);
//    } else {
//        _isChangePhoto = YES;
//        NSLog(@"🙂开始 保存了图片>>>%i", _isChangePhoto);
//    }
    NSDictionary *dic = [@"ScreenViewXy" getObjectValue];
    NSLog(@"🙂上一次保存的坐标>>>>%@", dic);

    _isChangePhoto = NO;

    _equipmentScreenSettingView = [[SNEquipmentScreenImageView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - FitSimpleIpx(20, 44))];
    [self.view addSubview:_equipmentScreenSettingView];

    // 获取屏保相关的按钮的状态
    [KK_BLESend sendGetDeviceIsCanSetScreenImage:^(id object, KKBLEAcceptType type) {
     }];

    weakSelf(weakSelf);
    _equipmentScreenSettingView.block = ^(id _Nonnull sender) {
        strongSelf(strongSelf);
        if ([sender isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)sender;
            if (btn.tag == 100) {
                // 照相
                [strongSelf openMediaType:UIImagePickerControllerSourceTypeCamera];
            } else if (btn.tag == 200) {
                // 相册
                [strongSelf openMediaType:UIImagePickerControllerSourceTypePhotoLibrary];
            } else if (btn.tag == 300) {
                [strongSelf.navigationController popViewControllerAnimated:YES];
            } else if (btn.tag == 400) {
                [strongSelf saveAction:btn];
            } else {
            }
        } else if ([sender isKindOfClass:[ZJSwitch class]]) {
            ZJSwitch *zjswitch = (ZJSwitch *)sender;
            if (zjswitch.tag == 666) {
                // 是否显示步数
                strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden = !strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden;
                if (strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden) {
                    int stepH = strongSelf.equipmentScreenSettingView.screenView.frame.size.height - self.stepHeight;
                    [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, stepH)];
                } else {
                    strongSelf.equipmentScreenSettingView.screenView.stepImageView.tintColor   = strongSelf.equipmentScreenSettingView.currentSelectButton.backgroundColor;//此时显示改变颜色后的图片
                    strongSelf.equipmentScreenSettingView.screenView.stepImageView.contentMode = UIViewContentModeScaleAspectFit;
                    if (strongSelf.equipmentScreenSettingView.screenView.frame.origin.y > strongSelf.equipmentScreenSettingView.backImageView.frame.size.height - self.timeHeight - self.stepHeight) {
                        [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y - self.stepHeight, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, strongSelf.equipmentScreenSettingView.screenView.frame.size.height + self.stepHeight)];
                    } else {
                        int stepH = strongSelf.equipmentScreenSettingView.screenView.frame.size.height + self.stepHeight;
                        [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, stepH)];
                    }
                }
            } else if (zjswitch.tag == 999) {
                strongSelf.equipmentScreenSettingView.bgView.hidden = !strongSelf.equipmentScreenSettingView.bgView.hidden;
//                [KK_BLESend sendScreenImageOpenState:zjswitch.on WithBlock:^(id object, KKBLEAcceptType type) {
//
//                }];
            }
        }
    };

    // 图片发送进度
    KK_BLESend.imageSendBlock = ^(NSInteger current, NSInteger all) {
        int value = 100.0*1.0*(current+1)/all;
        NSLog(@"发送进度>>>%d", value);
//        [weakSelf.view addSubview:weakSelf.bgView];
        weakSelf.bgView.hidden = NO;
        [weakSelf.showView.progressView setProgress:value / 99.9];
        weakSelf.showView.progressLabel.text = [NSString stringWithFormat:@"%d%@", value, @"%"];
        if (value == 100) {
//            [weakSelf.bgView removeFromSuperview];
            weakSelf.bgView.hidden = YES;
            weakSelf.isChangePhoto = NO;
            weakSelf.isFinish = YES;
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendImageFail) object:nil];
            if (_saveImage) {
                NSLog(@"🙂发送完成 保存图片成功>>>>>");
                [self saveImageDocuments:[UIImage imageCompressForSize:_saveImage targetSize:CGSizeMake(240, 240)]];
//                UIImageWriteToSavedPhotosAlbum(_saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
            } else {
                NSLog(@"🙂发送完成 保存图片失败>>>>>");
            }
        }
    };
    // 开启高速通道成功或者失败
    KK_BLESend.stateBlock = ^(NSInteger type) {
        weakSelf.isFinish = NO;

    };

    self.showView = [[OTAShowView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH -80, 150)];
    [self.showView showViewProgress:SN_Text(@"数据传输中...")];
    self.showView.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);

    _bgView                 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    [_bgView addSubview:self.showView];
    [self.view addSubview:_bgView];
    _bgView.hidden = YES;
}

- (void)saveAction:(UIButton *)sender {
    SHOWMBProgressHUD(SN_Text(@"保存中..."), nil, nil, nil, 1);
    if (KK_BLEModel.isConnected) {
        // 保存时间和步数所在的父视图的坐标
        int          x    = self.equipmentScreenSettingView.screenView.frame.origin.x;
        int          y    = self.equipmentScreenSettingView.screenView.frame.origin.y;
        NSDictionary *dic = @{@"x":[NSNumber numberWithInt:x], @"y":[NSNumber numberWithInt:y]};
        [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"ScreenViewXy"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        sender.enabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            sender.enabled = YES;
        });
        // 1.发送屏保按钮状态
        [KK_BLESend sendScreenImageOpenState:_equipmentScreenSettingView.openSwitch.on WithBlock:^(id object, KKBLEAcceptType type) {
             if (type == BLTAcceptTypeDataScreenImageSwitchState) {
                 SHOWMBProgressHUD(SN_Text(@"保存成功"), nil, nil, nil, 1);
             }
         }];
    } else {
        SHOWMBProgressHUD(nil, SN_Text(@"设备未连接"), nil, NO, 2.0);
    }
}

// 生成文件 118118
- (void)makeImageFileWith:(UIImage *)image {
    self.isFinish = NO;
    JHFeilterManager *manager   = [JHFeilterManager new];
    NSString         *imagePath = [manager createImageDataWithImage:image writetype:1];

    KK_BLESend.sendPath = imagePath;
    if (KK_BLEModel.isConnected && KK_BLESend.sendPath.length > 0) {
        [KK_BLESend sendImageData:YES WithBlock:^(id object, KKBLEAcceptType type) {
         }];
        _bgView.hidden = NO;
        [self.showView.progressView setProgress:0 / 99.9];
        self.showView.progressLabel.text = [NSString stringWithFormat:@"%d%@", 0, @"%"];
//        [[XNProgressHUD shared]showWithTitle:SN_Text(@"开始发送图片") maskType:XNProgressHUDMaskTypeBlack];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendImageFail) object:nil];
        [self performSelector:@selector(sendImageFail) withObject:nil afterDelay:60];
    } else {
        [self performSelector:@selector(delayShowInfo2) withObject:nil afterDelay:1.0];
    }
}

- (void)sendImageFail
{
    NSLog(@"🙂>>>>>>>%i",self.isFinish);
    if (self.isFinish) {
        return;
    }
    
    _bgView.hidden = YES;
    [_bgView removeAllSubviews];
    [_bgView removeFromSuperview];
    _bgView = nil;
    [[XNProgressHUD shared]showWithTitle:@"保存失败"];
}

- (void)delayShowInfo2 {
    SHOWMBProgressHUD(SN_Text(@"蓝牙未连接或者没有选择图片"), nil, nil, NO, 1.0);
    self.isFinish = YES;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendImageFail) object:nil];
}

- (void)openMediaType:(UIImagePickerControllerSourceType)type {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];

    imagePickerController.sourceType    = type;
    imagePickerController.delegate      = self;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    [self checkVideoStatus];
}

- (void)checkVideoStatus {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    switch (authStatus) {
    case AVAuthorizationStatusNotDetermined:
        //没有询问是否开启相机

        break;
    case AVAuthorizationStatusRestricted:
        //未授权，家长限制

        break;
    case AVAuthorizationStatusDenied:
    {
        //未授权
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:SN_Text(@"相机功能被禁止，是否开启？") message:nil preferredStyle:UIAlertControllerStyleActionSheet];

        [alertController addAction:[UIAlertAction actionWithTitle:SN_Text(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                    }]];

        [alertController addAction:[UIAlertAction actionWithTitle:SN_Text(@"退出") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                    }]];

        [alertController addAction:[UIAlertAction actionWithTitle:HHH_Text(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
                                    }]];

        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];

        [self presentViewController:alertController animated:YES completion:nil];
    }
    break;
    case AVAuthorizationStatusAuthorized:
        //玩家授权

        break;
    default:
        break;
    }
}

// 118118
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    _isChangePhoto = YES;
    NSLog(@"🙂 相册选择了图片>>>>>>>");
    UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    _equipmentScreenSettingView.backImageView.image = [UIImage imageCompressForSize:pickedImage targetSize:CGSizeMake(512, 512)];
    _saveImage                                      = [UIImage imageCompressForSize:pickedImage targetSize:CGSizeMake(240, 240)];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"取消");
    _isChangePhoto = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//保存图片
- (void)saveImageDocuments:(UIImage *)image {
    //拿到图片
    UIImage  *imagesave   = image;
    NSString *path_sandox = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png", KK_BLEModel.bleMAC]];
    
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(imagesave) writeToFile:imagePath atomically:YES];
    [self.equipmentScreenSettingView updateImageView];
}

// 读取
- (UIImage *)getDocumentImage {
    // 读取沙盒路径图片
    NSString *aPath3 = [NSString stringWithFormat:@"%@/Documents/%@.png", NSHomeDirectory(), KK_BLEModel.bleMAC];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl3 = [[UIImage alloc]initWithContentsOfFile:aPath3];

    // 图片保存相册
    return imgFromUrl3;
}

// 通知界面蓝牙状态
- (void)updateModel:(KKBLEModel *)model type:(KKBLEUpdateType)type {
    if (type == KKBLEUpdateDisConnect || type == KKBLEUpdatePowerOff || type == KKBLEUpdateDidConnect) {
        if (_bgView.hidden == NO) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendImageFail) object:nil];
//            [[XNProgressHUD shared]showWithTitle:SN_Text(@"保存失败")];
            _bgView.hidden = YES;
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:SN_Text(@"保存失败") message:SN_Text(@"设备未连接") preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction     *loginout        = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                                                      [self.navigationController popViewControllerAnimated:YES];
                                                  }];
            [loginout setValue:UIColorHEX(0x181818) forKey:@"titleTextColor"];
            [alertController addAction:loginout];

            [self presentViewController:alertController animated:YES completion:nil];
        }
    }
}

// 通知界面接收数据刷新相应界面的UI UpdateUiType
- (void)updateView:(KKBLEAcceptType)type {
    // 获取屏保相关的按钮的状态回调
    if (type == BLTAcceptTypeDataScreenSaverInfo) {
        // 是否开启屏保功能 118118
        [self.equipmentScreenSettingView updateImageView];

        if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"1"]) {
            self.equipmentScreenSettingView.openSwitch.on = YES;
            self.equipmentScreenSettingView.bgView.hidden = NO;
        } else if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"2"]) {
            // 隐藏操作界面
            self.equipmentScreenSettingView.openSwitch.on = NO;
            self.equipmentScreenSettingView.bgView.hidden = YES;
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(SCREENMORERENWIDTH, self.equipmentScreenSettingView.screenView.frame.size.height -self.timeHeight - self.stepHeight, self.timeHeight * 5, self.timeHeight + self.stepHeight)];
        } else {
        }

        // 步数按钮的开关
        if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"1"]) {
            self.equipmentScreenSettingView.stepOpenSwitch.on = YES;
        } else if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"2"]) {
            self.equipmentScreenSettingView.stepOpenSwitch.on = NO;
        } else {
        }

        // 获取设备支持屏保的字体种类及对应分辨率
        [KK_BLESend sendGetDeviceScreenSaverFontInfo:^(id object, KKBLEAcceptType type) {
         }];
    } else if (type == BLTAcceptTypeDataScreenSaverFontType) {
        NSLog(@"屏保时间步数显示参数回调");
        // 获取字体的相关值
        NSArray *array       = [[NSUserDefaults standardUserDefaults] objectForKey:@"FontWidthHight"];
        int     timeFontSize = [array[0] intValue];     // 16进制数
        int     timeW        = timeFontSize >> 8 & 0xff;    // 取高位为单个字体的宽  12:00 5个字
        int     timeH        = timeFontSize & 0xff;         // 取低位为单个字体的高

        int stepFontSize = [array[1] intValue];         // 16进制数
        int stepW        = stepFontSize >> 8 & 0xff;        // 取高位为单个字体的宽  00000 5个字
        int stepH        = stepFontSize & 0xff;             // 取低位为单个字体的高

        self.stepHeight = stepH;
        self.timeHeight = timeH;

        float x = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] ? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] : SCREENMORERENWIDTH;
        float y = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue] ? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue] : SCREENMORERENHEIGHT;
        if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"1"]) {
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(x, y, timeW * 5, stepH + timeH)];
        } else if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"2"]) {
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(x, y, timeW * 5, timeH)];
        } else {
        }

        [self.equipmentScreenSettingView.screenView.timeImageView setFrame:CGRectMake(0, 0, timeW * 5, timeH)];
        [self.equipmentScreenSettingView.screenView.stepImageView setFrame:CGRectMake(timeW * 5 - stepW * 5 - stepW, self.equipmentScreenSettingView.screenView.timeImageView.bottom, stepW * 5 + 16, stepH)];
    } else if (type == BLTAcceptTypeDataScreenStepLocation) {
        // 步数设置成功
        NSLog(@"🙂步数设置成功,开始发送图片%i", _isChangePhoto);

        NSString *path_sandox = NSHomeDirectory();
        //设置一个图片的存储路径
        NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/sendImage.png"]];

        if (_isChangePhoto) {
            NSLog(@"🙂开发发送新的图片>>>>>>>>11111");
            //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
            [UIImagePNGRepresentation(_saveImage) writeToFile:imagePath atomically:YES];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIImage *image222 = [[UIImage alloc]initWithContentsOfFile:imagePath];
                [self makeImageFileWith:image222];
            });
        } else {
            UIImage *localImage = [self getDocumentImage];
            if (localImage) {
                NSLog(@"🙂本地存在图片 设置其他参数>>>>>>>>22222");
                SHOWMBProgressHUD(SN_Text(@"保存成功"), nil, nil, nil, 1);
            } else {
                NSLog(@"🙂本地没有存在图片 发送默认图片>>>>>>33333");
                UIImage *image = [UIImage imageCompressForSize:_equipmentScreenSettingView.sendImage222 targetSize:CGSizeMake(240, 240)];
                _saveImage = image;
                //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
                [UIImagePNGRepresentation(_saveImage) writeToFile:imagePath atomically:YES];

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    UIImage *image222 = [[UIImage alloc]initWithContentsOfFile:imagePath];
                    [self makeImageFileWith:image222];
                });
            }
        }

//        if (_isChangePhoto) {
//            // 发送图片
//            [self makeImageFileWith:[self getDocumentImage]];
//        } else {
//            SHOWMBProgressHUD(SN_Text(@"保存成功"), nil, nil, nil, 1);
//        }
    } else if (type == BLTAcceptTypeDataScreenTimeLocation) {
        NSLog(@"时间设置成功");
        // 3.发送是否显示步数按钮状态
        // 屏保时间位置  (133,191)  (100,100)
        // 屏保步数位置 （167，218）

        int x = self.equipmentScreenSettingView.screenView.frame.origin.x + (self.equipmentScreenSettingView.screenView.width - self.equipmentScreenSettingView.screenView.stepImageView.width);
        int y = self.equipmentScreenSettingView.screenView.frame.origin.y + self.equipmentScreenSettingView.screenView.timeImageView.height;

        [KK_BLESend sendSetIsShowStepSwitchState:self.equipmentScreenSettingView.stepOpenSwitch.on type:BLTScreenSendTypeStep fontColor:self.equipmentScreenSettingView.currentSelectButton.backgroundColor x:x y:y fontType:0 withBlock:^(id object, KKBLEAcceptType type) {
         }];
    } else if (type == BLTAcceptTypeDataScreenImageSwitchState) {
        if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"1"]) {
            // 成功
            _equipmentScreenSettingView.openSwitch.on = YES;

            // 2.设置设备屏保显示时间的具体信息
            int x = self.equipmentScreenSettingView.screenView.frame.origin.x;
            int y = self.equipmentScreenSettingView.screenView.frame.origin.y;

            [KK_BLESend sendSetIsShowStepSwitchState:self.equipmentScreenSettingView.openSwitch.on type:BLTScreenSendTypeTime fontColor:self.equipmentScreenSettingView.currentSelectButton.backgroundColor x:x y:y fontType:1 withBlock:^(id object, KKBLEAcceptType type) {
             }];
        } else if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"2"]) {
            // 关闭
            _equipmentScreenSettingView.openSwitch.on = NO;
        } else {
        }
    } else {
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

@end
